package com.link.base.base.appinfo.service;

import com.link.base.base.appinfo.dao.mybatis.mapper.AppMobileInfoMapper;
import com.link.base.base.appinfo.model.AppMobileInfo;
import com.link.base.base.appinfo.model.AppMobileUser;
import com.link.base.base.appinfo.model.AppVersion;
import com.link.base.base.appinfo.model.LoadFlag;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.dao.siebel.mapper.BasicMapperSiebel;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.*;

/**
 * 设备管理
 *
 * @author ouyangzhenqiang
 * @date 2018/10/16
 */
@Service
public class AppMobileInfoServiceImpl extends BasicServiceImpl<AppMobileInfo> implements AppMobileInfoService {

    @Resource
    private AppMobileInfoMapper appMobileInfoMapper;
    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicMapper<AppMobileInfo> getBasicMapper() throws Exception {
        return appMobileInfoMapper;
    }

    @Override
    public Map<String, Object> queryDeviceNumber(AppMobileInfo record) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String[] devices = new String[5];
        devices[0] = "0";
        devices[1] = "0";
        devices[2] = "0";
        devices[3] = "0";
        devices[4] = "0";
        List<AppMobileInfo> list = appMobileInfoMapper.queryDeviceNumber(record);
        for (int i = 0; i < list.size(); i++) {
            if ("total".equals(list.get(i).getPlatFormType())) {
                devices[0] = list.get(i).getDeviceNum();
            } else if ("android".equals(list.get(i).getPlatFormType())) {
                devices[1] = list.get(i).getDeviceNum();
            } else if ("android pad".equals(list.get(i).getPlatFormType())) {
                devices[2] = list.get(i).getDeviceNum();
            } else if ("iphone".equals(list.get(i).getPlatFormType())) {
                devices[3] = list.get(i).getDeviceNum();
            } else if ("ipad".equals(list.get(i).getPlatFormType())) {
                devices[4] = list.get(i).getDeviceNum();
            }
        }
        result.put("result", devices);
        return result;
    }

    @Override
    public Map<String, Object> queryNewOrLiveNumber(AppMobileInfo record) throws Exception {
        LinkRedisClient j = null;
        Map<String, Object> result = new HashMap<>(4);
        try {
            j = RedisUtil.getJedis();
            // 查询7日内 新增设备
            List<AppMobileInfo> newList = appMobileInfoMapper.queryNewDeviceNumber(record);
            result.put("newList", newList);

            Date tempDate = new Date();
            String currentDate = DateUtil.dateToStr(tempDate, "yyyy-MM-dd");
            // 查询当日活跃设备
            AppMobileInfo liveDeviceNum = appMobileInfoMapper.queryLiveDeviceNumber(record);
            j.hset("app_live_device_num_report", currentDate, liveDeviceNum.getDeviceNum());
            // 加载缓存构造报表数据
            List<AppMobileInfo> liveList = new ArrayList<>();
            int reportDateNum = 7;
            for (int i = 1; i <= reportDateNum; i++) {
                String dateKey = DateUtil.dateToStr(DateUtil.addTimes(Calendar.DATE, tempDate, 0 - (reportDateNum - i)), "yyyy-MM-dd");
                AppMobileInfo appMobileInfo = new AppMobileInfo();
                appMobileInfo.setLastUpdated(dateKey);
                String liveNum = j.hget("app_live_device_num_report", dateKey);
                appMobileInfo.setDeviceNum(StringUtils.isBlank(liveNum) ? "0" : liveNum);
                liveList.add(appMobileInfo);
            }
            result.put("liveList", liveList);
        } finally {
            RedisUtil.returnResource(j);
        }
        return result;
    }

    @Override
    public void refreshLiveNumber() throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            Date tempDate = new Date();
            String currentDate = DateUtil.dateToStr(tempDate, "yyyy-MM-dd");
            // 查询当日活跃设备
            AppMobileInfo record = new AppMobileInfo();
            AppMobileInfo liveDeviceNum = appMobileInfoMapper.queryLiveDeviceNumber(record);
            j.hset("app_live_device_num_report", currentDate, liveDeviceNum.getDeviceNum());
            Map<String, String> liveNumList = j.hgetAll("app_live_device_num_report");
            if (liveNumList.size() > 30) {
                // 清理30天以前的数据，保险起见尝试多删除几天
                for (int i = 0; i < 5; i++) {
                    String dateKey = DateUtil.dateToStr(DateUtil.addTimes(Calendar.DATE, tempDate, -30 - i), "yyyy-MM-dd");
                    j.hdel("app_live_device_num_report", dateKey);
                }
            }
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    @Override
    public Map<String, Object> queryMobileTypeNumber(AppMobileInfo record) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<AppMobileInfo> mobileTypeList = appMobileInfoMapper.queryMobileTypeNumber(record);
        result.put("mobileTypeList", mobileTypeList);
        return result;
    }

    @Override
    public Map<String, Object> queryProvinceNumber(AppMobileInfo record) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<AppMobileInfo> mobileProvinceList = appMobileInfoMapper.queryProvinceNumber(record);
        result.put("mobileProvinceList", mobileProvinceList);
        return result;
    }

    @Override
    public void submit(AppMobileInfo record) throws Exception {
        // 判断设备是否已经注册
        List<AppMobileInfo> appMobileInfoList = appMobileInfoMapper.mobileCheck(record);
        if (appMobileInfoList != null && appMobileInfoList.size() > 0) {
            // 设备已注册，则更新设备绑定的用户信息
            appMobileInfoMapper.mobileInfoUpdate(record);

            // 判断设备与用户中间表是否存在，不存在则新建
            AppMobileInfo appMobileInfo = appMobileInfoList.get(0);
            AppMobileUser appMobileUser = new AppMobileUser();
            appMobileUser.setDeviceId(appMobileInfo.getId());
            appMobileUser.setUserId(Long.parseLong(record.getUserId()));
            int count = appMobileInfoMapper.mobileUserCheck(appMobileUser);
            if (count == 0) {
                // 创建设备与用户中间表记录
                appMobileUser.setId(keyGenerateService.keyGenerate());
                appMobileInfoMapper.mobileUserInsert(appMobileUser);
            }
        } else {
            // 设备未注册，则新建设备信息记录
            Long deviceId = keyGenerateService.keyGenerate();
            record.setId(deviceId);
            appMobileInfoMapper.insert(record);

            // 创建设备与用户中间表记录
            AppMobileUser appMobileUser = new AppMobileUser();
            appMobileUser.setId(keyGenerateService.keyGenerate());
            appMobileUser.setDeviceId(deviceId);
            appMobileUser.setUserId(Long.parseLong(record.getUserId()));
            appMobileInfoMapper.mobileUserInsert(appMobileUser);
        }
    }

    @Override
    public void clearUser(AppMobileInfo record) throws Exception {
        LCLogger.info().withMessageKey("clearUser(AppMobileInfo record)").withMessage("清除用户和设备之间的关联，uuid => " + record.getUuid()).flush();
        appMobileInfoMapper.mobileClearUpdate(record);
    }

    @Override
    public List<AppMobileInfo> getMobileInfo(AppMobileInfo record) throws Exception {
        return appMobileInfoMapper.getMobileInfo(record);
    }


    @Override
    public BasicMapperSiebel<AppMobileInfo> getSiebelBasicMapper() throws Exception {
        return null;
    }

    @Override
    public AppVersion getAppVersion(String appId) throws Exception {
        AppVersion appVersion = new AppVersion();
        String redisKey = "app_info_" + appId;
        LCLogger.info().withMessageKey("getAppVersion(String appId)").withMessage("版本检测 => redisKey: " + redisKey).flush();
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // 应用ID
            appVersion.setAppType(j.hget(redisKey, "bundleId"));
            // 企业级大版本号
            appVersion.setAppLV(j.hget(redisKey, "appLV"));
            // 企业级小版本号
            appVersion.setAppMV(j.hget(redisKey, "appMV"));
            // 版本更新提示
            appVersion.setUpdateTips(j.hget(redisKey, "updateTips"));
            // iOS更新包大小
            appVersion.setIpaSize(j.hget(redisKey, "ipaSize"));
            // 安卓更新包大小
            appVersion.setApkSize(j.hget(redisKey, "apkSize"));
            // 版本更新日期
            appVersion.setUpdateDt(j.hget(redisKey, "updateDt"));
            // apk下载地址
            appVersion.setApkUrl(j.hget(redisKey, "apkDownloadUrl"));
            // ipa下载地址
            appVersion.setIpaUrl(j.hget(redisKey, "ipaDownloadUrl"));
            // 应用下载地址
            appVersion.setDownloadUrl(j.hget(redisKey, "appDownloadUrl"));
            appVersion.setAnonymousFlag("Y");
        } finally {
            RedisUtil.returnResource(j);
        }
        return appVersion;
    }

    @Override
    public List<LoadFlag> getLoadDataFlag(LoadFlag temp) throws Exception {
        return appMobileInfoMapper.getLoadDataFlag(temp);
    }

    @Override
    public List<AppMobileUser> mobileUserList(AppMobileUser record) throws Exception {
        return appMobileInfoMapper.mobileUserListPage(record);
    }

}
